#include "testmovetothread.h"

#include "qdebug.h"
#include "qmessagebox.h"
#include <chrono>
#include <thread>

void testmovetothread::on_pushButton_start_clicked()
{
    emit signal_start("fuck");
}

void testmovetothread::OnFinished()
{
    qDebug() << __func__ << " " << "finished";
    QMessageBox::information(this, "information", "finished");
}

void testmovetothread::on_pushButton_quit_clicked()
{
    if (m_thread)
    {
        m_thread->quit();
        m_thread->wait();
    }
}

testmovetothread::testmovetothread(QWidget *parent)
    : QMainWindow(parent)
    , m_thread{}
    , m_worker{}
{
    ui.setupUi(this);
    if (nullptr == m_thread)
        m_thread = new QThread(this);
    Q_ASSERT(m_thread);
    if (nullptr == m_worker)
        m_worker = new CWorkThread();
    Q_ASSERT(m_worker);
    connect(m_thread, &QThread::finished, m_worker, &QObject::deleteLater);
    connect(m_worker, &CWorkThread::signal_finished, this, &testmovetothread::OnFinished);
    connect(this, &testmovetothread::signal_start, m_worker, &CWorkThread::dowork);
    m_worker->moveToThread(m_thread);
    m_thread->start();
}

testmovetothread::~testmovetothread()
{
    on_pushButton_quit_clicked();
}


void CWorkThread::dowork(const QString&msg)
{
    
    do {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        qDebug() << "__func__" << " " << msg << endl;
        emit signal_finished();
        break;
    } while (true);

}